package com.travel.config;

import com.wechat.pay.java.core.RSAPublicKeyConfig;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.util.stream.Collectors;

/**
 * @ClassName com.ruoyi.common.config
 * @Description
 * @Author Hardy
 * @Time 2024/05/11 14:23
 * 小程序支付配置类
 */
@Component
@Data
@Slf4j
@ConfigurationProperties(prefix = "wx")
public class PayInfoConfig {

    /**
     * 应用编号
     */
    private String appId;
    /**
     * 商户号
     */
    private String mchId;
    /**
     * 公钥
     */
    private String publicKeyId;
    /**
     * 公钥
     */
    private String publicKeyPath;
    /**
     * APIv3密钥
     */
    private String apiV3Key;
    /**
     * 支付通知回调地址
     */
    private String notifyUrl;
    /**
     * 退款回调地址1
     */
    private String refundNotifyUrl;

    /**
     * API 证书中的 key.pem
     */
    private String keyPemPath;

    /**
     * 商户序列号
     */
    private String MchSerialNo;


    /**
     * 获取私钥
     *
     * @param filename 私钥文件路径
     * @return 私钥对象
     */
    public static PrivateKey getPrivateKey(String filename) throws IOException {
        InputStream inputStream = new ClassPathResource(filename
                .replace("classpath:", "")).getInputStream();
        String content = new BufferedReader(new InputStreamReader(inputStream))
                .lines().collect(Collectors.joining(System.lineSeparator()));
        try {
            String privateKey = content.replace("-----BEGIN PRIVATE KEY-----", "")
                    .replace("-----END PRIVATE KEY-----", "")
                    .replaceAll("\\s+", "");

            KeyFactory kf = KeyFactory.getInstance("RSA");
            return kf.generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey)));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("当前Java环境不支持RSA", e);
        } catch (InvalidKeySpecException e) {
            throw new RuntimeException("无效的密钥格式");
        }
    }


    /**
     * 获取公钥
     *
     * @param filename
     * @return
     */
    public static String getPublicKey(String filename) throws IOException {
        InputStream inputStream = new ClassPathResource(filename
                .replace("classpath:", "")).getInputStream();
        String content = new BufferedReader(new InputStreamReader(inputStream))
                .lines().collect(Collectors.joining(System.lineSeparator()));
        String publicKey = content.replace("-----BEGIN PUBLIC KEY-----", "")
                .replace("-----END PUBLIC KEY-----", "")
                .replaceAll("\\s+", "");
        return publicKey;
    }

    @Bean
    public RSAPublicKeyConfig rsaAutoCertificateConfig() throws IOException {
        PrivateKey privateKey = getPrivateKey(keyPemPath);
        String publicKey = getPublicKey(publicKeyPath);
        RSAPublicKeyConfig config = new RSAPublicKeyConfig.Builder()
                .merchantId(mchId)
                .publicKey(publicKey)
                .privateKey(privateKey)
                .publicKeyId(publicKeyId)
                .merchantSerialNumber(MchSerialNo)
                .apiV3Key(apiV3Key)
                .build();
        return config;
    }

}
